package com.appkubes.mall.restful.application.wx.controller;

import com.alibaba.fastjson.JSON;
import com.appkubes.common.utils.net.HttpClientUtils;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.restful.application.common.base.BaseController;
import com.appkubes.mall.restful.application.wx.service.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api("二维码模块")
@RestController
@RequestMapping("/api/Cqrcode")
public class QrcodeController extends BaseController {

    @Autowired
    WxService wxService;

    @Value("${ConfigValue.qrcodePath}")
    protected String qrcodePath;

    @ApiOperation(value = "获取小程序码")
    @PostMapping("/getQrcode")
    public Object getQrcode(
            @RequestParam(defaultValue = "") String page,
            @RequestParam(defaultValue = "") String scene) throws Exception{
        //两步
        //1,获取accesstoken
        String accessToken = wxService.getAccessToken();
        //2,获取图片
        String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
        //获取小程序页面路径
        Map<String,String> map = new HashMap<>();
        map.put("page",page);
        map.put("scene",scene);
        String jsonString = JSON.toJSONString(map);
        okhttp3.Response response = HttpClientUtils.post(url,jsonString);
        InputStream inputStream = response.body().byteStream();
        String newFile = qrcodePath+"images/ma/";
        String rebackFile = "images/ma/";
        String fileName = DateUtils.DateToTimestamp(new Date())+(Math.random()*900 + 100)+".png";

        File file = new File(newFile+fileName);
        if (!file.exists()) {
            //file.createNewFile();
            file.getParentFile().mkdirs();
        }
        OutputStream outputStream = new FileOutputStream(file);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = inputStream.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.flush();
        //file_put_contents($new_file.$file_name,$img_data[1]);
        return this.imgResponse(rebackFile + fileName);
    }

}
